import { ApiResponse, Channel, Channels } from '@/types/data'
import { ChannelAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { hasToken } from '@/utils/storage'
import { getChannel, setChannel } from '@/utils/storageChannel'

export const getUserChannel = (): RootThunkAction => {
  // console.log(data)
  // 1. 登录用户，直接发请求
  return async (dispatch) => {
    if (hasToken()) {
      const res = await request.get<ApiResponse<{channels:Channels}>>('/user/channels')
      console.log(res.data.data.channels)
      dispatch({
        type: 'channel/getChannel',
        payload: res.data.data.channels
      })
    } else {
      // 2. 没有登录
      const channels = getChannel()
      //  （1）本地拿
      if (channels.length > 0) {
        dispatch({
          type: 'channel/getChannel',
          payload: channels
        })
      } else {
        //  （2）发请求，做持久化
        const res = await request.get<ApiResponse<{channels:Channels}>>('/user/channels')
        const channels = res.data.data.channels

        setChannel(channels)

        dispatch({
          type: 'channel/getChannel',
          payload: channels
        })
      }
    }
  }
}

export function getAllChannel (): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ channels: Channels }>>(
      '/channels'
    )
    dispatch({
      type: 'channel/saveAllChannels',
      payload: res.data.data.channels
    })
  }
}

export const changeActive = (id: string): ChannelAction => {
  return {
    type: 'channel/changeActive',
    payload: id
  }
}

export const addChannel = (channel: Channel) : RootThunkAction => {
  return async (dispatch) => {
    if (hasToken()) {
      // 发请求调用接口，做添加
      await request.patch('/user/channels', { channels: [channel] })

      dispatch(getUserChannel())
    } else {
      // 本地添加
      const channels = getChannel()
      channels.push(channel)
      setChannel(channels) // 保存到localstorage

      //  保存到redux ---> 视图更新
      dispatch({
        type: 'channel/getChannel',
        payload: channels
      })
    }
  }
}

export const delChannel = (id: number) : RootThunkAction => {
  return async (dispatch) => {
    if (hasToken()) {
      // 发请求调用接口，做删除
      await request.delete('/user/channels/' + id)

      dispatch(getUserChannel())
    } else {
      // 本地删除
      const channels = getChannel()
      // 删除id为 id的那一项
      const newChannels = channels.filter(it => it.id !== id)

      setChannel(newChannels) // 保存到localstorage

      //  保存到redux ---> 视图更新
      dispatch({
        type: 'channel/getChannel',
        payload: newChannels
      })
    }
  }
}
